package com.xuhai.blog.admin.controller;


import com.xuhai.blog.admin.entity.UserEntity;
import com.xuhai.blog.admin.service.UserService;
import com.xuhai.blog.common.form.PasswordForm;
import com.xuhai.blog.common.form.UserForm;
import com.xuhai.blog.common.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author 机蜂
 * @since 2022-02-08
 */
@RestController
@RequestMapping("/admin/user")
public class UserController extends AbstractController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ResultJson list(){
        return ResultJson.ok().data(userService.list());
    }

    @PostMapping("/update")
    public ResultJson update(@RequestBody UserForm userForm){
        userService.update(userForm.toEntity());
        return ResultJson.ok();
    }

    @DeleteMapping("/delete/{userId}")
    public ResultJson delete(@PathVariable Integer userId){
        if(userId.equals(getUserId())){
            return ResultJson.error("无法删除当前登录用户");
        }
        userService.removeById(userId);
        return ResultJson.ok();
    }

    /**
     * 查询当前登录用户的信息
     * */
    @GetMapping("/info")
    public ResultJson info(){
        return ResultJson.ok().data(userService.getById(getUserId()));
    }

    /**
     * 根据传递的userId查询用户信息
     * */
    @GetMapping("/info/{userId}")
    public ResultJson info(@PathVariable Integer userId){
        return ResultJson.ok().data(userService.getById(userId));
    }

    @PostMapping("/password")
    public ResultJson password(@RequestBody PasswordForm passwordForm){
        passwordForm.setUserId(getUserId());
        userService.updatePassword(passwordForm);
        return ResultJson.ok();
    }

    @GetMapping("/page")
    public ResultJson page(int page, int limit, UserEntity user){
        user.setUserId(getUserId());
        return ResultJson.ok().data(userService.getPage(page,limit,user));
    }
}

